<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2016-8-16
 * Func   程序公共函数库
 */
defined('IN_YuLin') || exit('NO PERMIT!');

/***
 * @param $fileKey 上传文件的字段值
 * @return array stat表示上传结果0表示上传失败 1表示上传成功  file_url表示文件路径
 */
function UploadFile($fileKey)
{
    $data=[];
    $allow=['gif','jpg','jpeg','png'];
    $result=['error'=>1,'url'=>''];
    if($_FILES[$fileKey]['size'])
	{
        $pathInfo = pathinfo($_FILES[$fileKey]['name']);
        $ext = strtolower($pathInfo['extension']);
        if(in_array($ext,$allow))
		{
            $result['url'] = 'data/upload/'.date('Y/md/YmdHis').rand(1000,9999).'.'.$ext;
			
			$upfile = ROOT_PATH.$result['url'];
			@mkdir(dirname($upfile),0777,true);
			
            $rs=move_uploaded_file($_FILES[$fileKey]['tmp_name'],$upfile);
			$rs && $result['error'] = 0;
        }
    }

    return $result;
}

/**
 * 上传图片到七牛
 * 返回true表示上传成功  false表示上传失败
 */
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;
function QiNiuUpload($key,$file){
    spl_autoload_register('classLoader');
	classLoader('Qiniu/functions');
    // 构建鉴权对象
    $auth = new Auth(QINIU_ACCESS, QINIU_SECRET);

    // 生成上传 Token
    $token = $auth->uploadToken(QINIU_BUCKET);

    // 初始化 UploadManager 对象并进行文件的上传。
    $uploadMgr = new UploadManager();

    // 调用 UploadManager 的 putFile 方法进行文件的上传。
    list($ret, $err) = $uploadMgr->putFile($token, $key, $file);
    if ($err !== null) {
        //var_dump($err);
        return false;
    } else {
        return true;
        //var_dump($ret);
    }
}

//获取七牛图片
function QiNiuPic($key,$width=0,$height=0){
    $picUrl="/upfile/".$key;
    return $picUrl;
}

//删除七牛文件
/**
 * 删除七牛文件
 * true表示删除成功  fasle表示删除失败
 */
use Qiniu\Storage\BucketManager;
function QiNiuDelPic($key){
    spl_autoload_register('classLoader');
	classLoader('Qiniu/functions');
    //初始化Auth状态：
    $auth = new Auth(QINIU_ACCESS, QINIU_SECRET);

    //初始化BucketManager
    $bucketMgr = new BucketManager($auth);

    //删除$bucket 中的文件 $key
    $err = $bucketMgr->delete(QINIU_BUCKET, $key);
    //echo "\n====> delete $key : \n";
    if ($err !== null) {
        return false;
    } else {
        return true;
    }

}

/**
 * @param $class
 * 加载类
 */
function classLoader($class)
{
    $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    $file = LIB_PATH . $path . '.php';

    if (file_exists($file)) {
        require_once $file;
    }
}

/**
 * 创建百度富编辑器
 */
function createUEditor($key="content",$value="")
{
    echo '<script src="'.URL.'lib/ueditor/ueditor.config.js"></script>';
    echo '<script src="'.URL.'lib/ueditor/ueditor.all.min.js"></script>';
    echo '<script src="'.URL.'lib/ueditor/lang/zh-cn/zh-cn.js"></script>';
    echo '<script id="editor_'.$key.'" name="'.$key.'" type="text/plain" style="width:100%;height:300px;">'.$value.'</script>';
    echo '<script type="text/javascript">';
    echo 'var _ue = UE.getEditor("editor_'.$key.'");';
    if(!$value)
    {
        //echo 'setTimeout(\'_ue.setContent(UE.getEditor("editor_'.$key.'").execCommand("getlocaldata"))\',2000);';
    }    
    echo '</script>';
}

//  分页
function Multi($url,$page,$total,$size = 20)
{
    $pages = max(1,ceil($total / $size));  //总页数
    
	$url = str_replace('&','&amp;',$url);	//	以防部分参数在ff和gg浏览器出现问题
	
    $multi = '<div class="page">';
    $multi.= '<a href="'.$url.'&page=1" class="ctl'.($page > 1 ? '' : ' disabled').'">|&lt;</a>';
	$prev=($page - 1)>0 ? ($page - 1) : 1;
	$multi.= '<a href="'.$url.'&page='.$prev.'" class="ctl">&lt;</a>';
    
    $start = max(1,$page - 4);
    $end = min($start + 9,$pages);
    for($i = $start; $i <= $end; $i++)
    {
        $multi .= '<a href="'.$url.'&page='.$i.'"'.($i == $page ? ' class="current"' : '').'>'.$i.'</a>';
    }
    $end < $pages && $multi .= '<span>...</span><a href="'.$url.'&page='.$pages.'">'.$pages.'</a>';
    $next=($page + 1) >= $pages ? $pages : ($page + 1);
    $multi.= '<a href="'.$url.'&page='.$next.'" class="ctl">&gt;</a>';
    $multi.= '<a href="'.$url.'&page='.$pages.'" class="ctl'.($page < $pages ? '' : ' disabled').'">&gt;|</a>';
    $multi.= '</div>';
    
    return $multi;
}

/**
 * 会员和后台管理员的加密算法
 */
function Password($passWord)
{
    $md5=md5($passWord.'#d2lji%C0Jeiba#H%GG2AjAeLc^Xv');
    return md5('XNPvNlKA5%wsvIA$Ho*5DFyTE19Ke8HP!RKd'.$md5);
}

// 获取客户端ip
function GetIp()
{
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
    {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } 
    elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown'))
    {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } 
    elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
    {
        $onlineip = getenv('REMOTE_ADDR');
    } 
    elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
    {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    if (!preg_match('/[\d\.]{7,15}/', $onlineip))
    {
        $onlineip = '0.0.0.0';
    }
    return $onlineip;
}

// 去掉非法字符
function NoBadStr($str)
{
    //$str = str_replace(' ','',$str);
    $str = str_replace('%20','',$str);
	$str = str_replace('%27','',$str);
	$str = str_replace('"','&quot;',$str);
	$str = str_replace("'",'',$str);
	$str = str_replace("\"",'',$str);
	$str = str_replace('<','&lt;',$str);
	$str = str_replace('>','&gt;',$str);
	$str = str_replace('(','',$str);
	$str = str_replace(')','',$str);
	$str = str_replace("{",'',$str);
	$str = str_replace('}','',$str);
	return $str;
}

//	html去掉非法字符
function NoBadHtml($html)
{
	$html = preg_replace('/<\/?script[^>]*>/i','',$html);
	$html = str_replace('<br/><br/>','<br/>',$html);
	$html = str_replace('<p><br/>','<p>',$html);
	$html = str_replace('</p><br/>','</p>',$html);
	$html = str_replace('<p></p>','',$html);
	$html = str_replace('<html>','&lt;html&gt;',$html);
	$html = str_replace('<body>','&lt;body&gt;',$html);
	$html = str_replace('</html>','&lt;/html&gt;',$html);
	$html = str_replace('</body>','&lt;/body&gt;',$html);
	$html = trim($html);
	
	return $html;
}

// 裁剪字符
function CutStr($string, $length, $dot = '...', $charset = 'utf-8')
{
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower($charset) == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while($n < $strlen)
		{
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) break;
		}
		if($noc > $length) $n -= $tn;
		$strcut = substr($string, 0, $n);
	}
	else
	{
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		for($i = 0; $i < $maxi; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

//  mobile validator
function CheckMobile($mobile)
{
	return strlen($mobile) == 11 && preg_match('/^1[34578]\d{9}$/',$mobile);
}

//  email validator
function CheckEmail($email)
{
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

// 加密解密
function AuthCode($string, $operation = 'DECODE', $key = '', $expiry = 0) 
{
	$ckey_length = 4;
	$key = md5($key ? $key : AUTH_KEY.$_SERVER['HTTP_USER_AGENT']);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

// 用AES/ECB/PKCS5Padding算法加密/解密字符串
function Pkcs5padding ($text, $blocksize)
{
	$pad = $blocksize - (strlen($text) % $blocksize);
	return $text . str_repeat(chr($pad), $pad);
}
function AesCode($string, $type = 'encode', $key = '')
{
    if(!$string)
    {
        return '';
    }
    
	$key = $key ? $key : API_KEY;
	
	if($type == 'encode')	//	加密
	{
		$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
		$string = Pkcs5padding($string, $size);
		$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
		$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		mcrypt_generic_init($td, $key, $iv);
		$data = mcrypt_generic($td, $string);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		$data = base64_encode($data);
	}
    else	//	解密
	{
		$decrypted= mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($string), MCRYPT_MODE_ECB); 
		$dec_s = strlen($decrypted);
		$padding = ord($decrypted[$dec_s-1]);
		$data = substr($decrypted, 0, -$padding);
	}
    
    return $data;
}

// 设置cookie
function set_cookie($var, $value = '', $time = 0)
{
	$time = $time > 0 ? ($time + TIMESTAMP) : ($value == '' ? TIMESTAMP - 3600 : 0);
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = COOKIE_PREV.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
		}
	}
	else
	{
		setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
	}
}

// 获取cookie
function get_cookie($var)
{
	$var = COOKIE_PREV.$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}

// 生成insert语句
function CreateInsertSql($arr)
{
    return '(`'.implode('`,`',array_keys($arr)).'`) VALUES(\''.implode('\',\'',$arr).'\')';
}

// 生成update语句
function CreateUpdateSql($arr, $sep = ',')
{
    $sql = $com = '';
    foreach($arr as $k => $v)
    {
        $sql .= $com.'`'.$k.'` = \''.$v.'\'';
        $com = $sep;
    }
    return $sql;
}

//  增加表前缀
function Table($name)
{
    global $db;
    
    return $db->table($name);
}

//  生成随机码
function CreateCode($tid = 'number',$len = 6)
{
    $str1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $str2 = '0123456789';
    
    //  随机码组合类型
    $str = $str1.$str2;
    if($tid == 'number')
    {
        $str = $str2;
    }
    else if($tid == 'string')
    {
        $str = $str1;
    }
    
    $code = '';
    $slen = strlen($str) - 1;
    for($i = 0; $i < $len; $i++)
    {
        $code .= $str[rand(0,$slen)];
    }
    
    return $code;
}

//	模拟post请求
function HttpPost($url, $param)
{
	$oCurl = curl_init ();
	if (stripos ( $url, "https://" ) !== FALSE) {
		curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
		curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false );
	}
	if (is_string ( $param )) {
		$strPOST = $param;
	} else {
		$aPOST = array ();
		foreach ( $param as $key => $val ) {
			$aPOST [] = $key . "=" . urlencode ( $val );
		}
		$strPOST = join ( "&", $aPOST );
	}
	curl_setopt ( $oCurl, CURLOPT_URL, $url );
	curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt ( $oCurl, CURLOPT_POST, true );
	curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST );
	$sContent = curl_exec ( $oCurl );
	$aStatus = curl_getinfo ( $oCurl );
	curl_close ( $oCurl );
	if (intval ( $aStatus ["http_code"] ) == 200) {
		return $sContent;
	}
	
	return false;
}

function ShowMsg($msg,$url='',$time=2)
{
    global $tpl, $tpl_msg;
	
    $url = str_replace(array("\n", "\r"), '', $url);
    !$msg && $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
	
	$tpl_msg = array('msg'=>$msg,'url'=>$url,'time'=>$time);
    $tpl->assign('tpl_msg',$tpl_msg);
    
    $tpl->display('index/showmsg');
    exit();
}

//  解析地址
function U($str = '',$arr = array())
{
    $tmp = explode('/',$str);
    $str = '';
    if(isset($tmp[0]))
    {
        $str .= '?';
        $tmp[0] && $str .= '&m='.$tmp[0];
        if(isset($tmp[1]))
        {
            $tmp[1] && $str .= '&c='.$tmp[1];
            if(isset($tmp[2]))
            {
                $tmp[2] && $str .= '&a='.$tmp[2];
            }
        }
		
		$t = array();
		foreach($arr as $k => $v)
		{
			$t[] = $k.'='.$v;
		}
		$t && $str .= '&'.implode('&',$t);
    }
    
    return str_replace('?&','?',$str);
}

//  permit：[m,c,a]，gid为会员组信息
function CheckPermit($permit,$group)
{
    //  1为保留组、index和api模块下文件都有权限，不需验证
    if($group['id'] == 1 || in_array($permit['m'],['index','api']))
    {
        return true;
    }
    
    global $db;
    
    if(!$group['permit'])
    {
        return false;
    }
    
    $menu = $db->getrow('SELECT * FROM '.Table('admin_menu').' WHERE m = \''.$permit['m'].'\' AND c = \''.$permit['c'].'\'');
    
    return $menu && in_array($menu['id'],explode(',',$group['permit']));
}

//	菜单是第几级
function MenuLevel($id,$menu,$i=0)
{
	foreach($menu as $val)
	{
		if($val['id'] == $id)
		{
			if($val['pid'] == '0') return $i;
			$i++;
			return MenuLevel($val['pid'],$menu,$i);
		}
	}
}

// 获取表单hash，加强表单输入验证
function FormHash() 
{
    return substr(md5(substr(TIMESTAMP, 0, -4).HASH_KEY), 16);
}

//	返回json结果
function AjaxReturn($error = 0,$msg = '',$data = [])
{
	if(is_array($error))	//	兼容以前小谢的程序
	{
		$msg = $error['msg'];
		$error = $error['error'];
	}
	
	$tmp = [];
	$tmp['error']	=	$error ? $error : 0;	//	错误码
	$tmp['status']	=	$tmp['error'] ? false : true;
	$tmp['msg']		=	$msg ? $msg : '';	//	错误消息
	$tmp['info']	=	$tmp['msg'];
	$tmp['data']	=	$data ? json_encode($data) : '[]';	//	返回内容
	
	echo json_encode($tmp);
	exit;
}

function UserLogin($url = '')
{
	global $_uid;
	if(!$_uid)
	{
		$url && $_SESSION['backurl'] = $url;
		
		header('Location: '.U('member/login'));
		exit;
	}
	
	return;
}

//	用户资金操作日志：余额和冻结资金
function MoneyLog($data)
{
	global $db;
	
	if($data['balance'] == 0 && $data['uid'] < 0)
	{
		return false;
	}
	
	//	是否已经操作过
	$tmp = $db->getrow('SELECT 1 FROM '.Table('user_money_log').' WHERE lkey = \''.$data['lkey'].'\'');
	if($tmp)
	{
		return false;
	}
	
	//	用户现有资金
	$money = $db->getrow('SELECT * FROM '.Table('user').' WHERE id = '.$data['uid']);
	
	$balance = bcadd($money['money'],$data['balance'],2);	//	操作后余额
	if($balance < 0)
	{
		return false;
	}
	$freeze = 0;	//	冻结金额
	
	//	资金日志
	$ins = [];
	$ins['uid']			=	$data['uid'];
	$ins['tid']			=	$data['tid'];
	$ins['lkey']		=	$data['lkey'];
	$ins['money']		=	$data['money'];
	$ins['balance']		=	$balance;
	$ins['freeze']		=	$freeze;
	$ins['total']		=	$balance + $freeze;
	$ins['balance_old']	=	$money['money'];
	$ins['freeze_old']	=	$freeze;
	$ins['total_old']	=	$money['money'];
	$ins['dateline']	=	TIMESTAMP;
	$ins['ip']			=	GetIp();
	$ins['notes']		=	$data['notes'];
	$id = $db->add('user_money_log',$ins);
	if(!$id)
	{
		return false;
	}
	
	/*
	$recharge = '';
	
	//	充值提成
	if($data['tid'] == 'recharge')
	{
		$recharge = ',recharge = recharge + '.$data['money'];
		
		$user = $db->getrow('SELECT mobile,upuid FROM '.Table('user').' WHERE id = '.$data['uid']);
		if($user['upuid'] > 0)
		{
			$tmp = [];
			$tmp['lkey']	=	str_replace('recharge','recharge_reward',$data['lkey']);
			$tmp['tid']		=	'recharge_reward';
			$tmp['uid']		=	$user['upuid'];
			$tmp['money']	=	intval($data['money'] * 0.05);	//	提成5%
			$tmp['freeze']	=	0;
			$tmp['balance']	=	$tmp['money'];
			$tmp['notes']	=	'上级充值返点：'.$user['mobile'];
			
			$res = MoneyLog($tmp);
		}
	}
	*/

	//	个人账户金额
	$db->exec('UPDATE '.Table('user').' SET money = '.$balance.' WHERE id = '.$data['uid']);
	
	return true;
}

//	计算阶乘
function Factorial($n)
{
	$res = 1;
	for($i = 1; $i <= $n; $i++)
	{
		$res *= $i;
	}
	
	return $res;
}

//	计算组合数
function NumGroup($n,$m)
{
	return Factorial($n) / Factorial($n - $m) / Factorial($m);
}

//	计算排列数
function NumQueen($n,$m)
{
	return Factorial($n) / Factorial($n - $m);
}

//截取字符串
function subtext($text, $length)
{
    if(mb_strlen($text, 'utf8') > $length) 
    return mb_substr($text, 0, $length, 'utf8').'...';
    return $text;
}

/**
 * @param $arr 需要组合数组
 * @param int $num 组合元素个数
 * @return array
 */
function getSequenceAry($arr,$num=1)
{
    $count = count($arr);
    $min   = min($count,$num);

    if($min<1){
        return false;
    }

    $return =array();
    for(;$min>=1;$min--){
        $arrRet = array();
        $max = $count-($min-1);
        for($i=0;$i<$max;$i++){
            getSequenceArySub($arr,$count,$min,$i,$arrRet,$return);

        }
    }
    return $return;

}

function getSequenceArySub($arr,$count,$min,$i,$arrRet=array(),& $return){
    if(empty($arr) || empty($count))
        return false;
    if(1==$min){
        $arrRet[--$min] = $arr[$i];
        $return[] = $arrRet;
    }else{
        $arrRet[--$min] = $arr[$i];
        for($j = $i+1;$j<($count);$j++){
            getSequenceArySub($arr,$count,$min,$j,$arrRet,$return);
        }
    }
}

/**
 * 根据ip转化为地址
 */
function getaddress($ip,$https=true,$method='get',$data=null)
{
	$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip;
	//1.初始化url
	$ch = curl_init($url);
	//2.设置相关的参数
	//字符串不直接输出,进行一个变量的存储
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	//判断是否为https请求
	if($https === true){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	}
	//判断是否为post请求
	if($method == 'post'){
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	//3.发送请求
	$str = curl_exec($ch);
	//4.关闭连接
	curl_close($ch);
	//返回请求到的结果
	$location = json_decode($str);
	return $location->country;
}

function k3odds()
{
	return array(
		'HE' => array(
			'3' => '189.00', 
			'4' => '63.00',
			'5' => '31.50',
			'6' => '18.90',
			'7' => '12.60',
			'8' => '9.00',
			'9'	=> '7.56',
			'10' => '7.00',
			'11' => '7.00',
			'12' => '7.56',
			'13' => '9.00',
			'14' => '12.60',
			'15' => '18.90',
			'16' => '31.50',
			'17' => '63.00',
			'18' => '189.00',
			'大' => '1.95',
			'小' => '1.95',
			'单' => '1.95',
			'双' => '1.95',
		),
		'STHTX' => '31.50',
		'STHDX' => '189.00',
		'SBTH' => '31.50',
		'SLHTX' =>'7.87',
		'ETHFX' => '12.60',
		'ETHDX' => '63.00',
		'EBTH' => '6.30'
	);
}

function GetEnPlayInfo()
{
    return array(
        'HE'=> '和值',
        'STHTX'=> '三同号通选',
        'STHDX'=> '三同号单选',
        'SBTH'=> '三不同号',
        'SLHTX'=> '三连号通选',
        'ETHFX'=> '二同号复选',
        'ETHDX'=> '二同号单选',
        'EBTH'=> '二不同号',
    );
}

/**
 * 充值后更新累计充值金额， 并检查是否满足升级情况
 */
function rechargeCheckLevel($data){
    if (!$data['uid'] || !$data['recharge_money'] || $data['recharge_money'] < 0){
        // 关键信息缺失，跳过
        return;
    }
    global $db;
    $userInfoTab = Table('user_info');
    $levelTab    = Table('user_level');
    $sql  = 'UPDATE ' . $userInfoTab . ' SET recharge_total = recharge_total+' . $data['recharge_money'] . ' WHERE uid = ' . $data['uid'];
    $db->exec($sql);
    // 检查是否需要升级
    $sql      = 'SELECT recharge_total, level_id FROM ' . $userInfoTab . ' WHERE uid = ' . $data['uid'];
    $userInfo = $db->getrow($sql);
    $sql      = 'SELECT id FROM ' . $levelTab . ' WHERE group_point <= ' . $userInfo['recharge_total'] . ' ORDER BY group_point DESC LIMIT 1';
    $checkLevelInfo = $db->getrow($sql);
    if ($checkLevelInfo['id'] != $userInfo['level_id']){
        $sql = 'UPDATE ' . $userInfoTab . ' SET level_id = ' . $checkLevelInfo['id'] . ' WHERE uid = ' . $data['uid'];
        $db->exec($sql);
    }
}    

/**
 * 根据用户的id来获取其一下级别的代理以及玩家
 * @param unknown $uid
 * @param unknown $data
 * @param number $lv
 * @param number $f_id: 所属父级
 * @param bool $is_self: 标识是否是调用者本身， 本身不返回
 */
function getUserLine($uid, &$data, $lv=1, $f_id=0, $is_self=true){
    global $db;
    $invcodeTab  = Table('user_invita_code');
    $invitemTab  = Table('user_invita_item');
    $userinfoTab = Table('user_info');
    $userTab     = Table('user');
    $sql         = 'SELECT u.`id`, u.`username`, u.`last_time`, info.`nickname`, info.`truename`, info.`invita_code_id`, info.`user_type`, info.`lower_nums`
                    FROM ' . $userTab . ' AS u
                    LEFT JOIN ' . $userinfoTab . ' AS info
                    ON u.id = info.`uid`
                    WHERE u.`id` = ' . $uid;
    $userInfo            = $db->getrow($sql);
    $userInfo['lv']      = $lv;
    $userInfo['f_id']    = $f_id;
    $userInfo['re_last_time'] = date('Y-m-d', $userInfo['last_time']);
    // 查询userinfo的返点配置
    $sql                 = 'SELECT lott_cate_id, re_point FROM ' . $invitemTab . ' WHERE code_id = ' . $userInfo['invita_code_id'];
    $itemData            = $db->getall($sql, 'lott_cate_id');
    $userInfo['invItem'] = $itemData;
    if (!$is_self){
        $data[$uid]          = $userInfo;
    }
    $is_self     = false;
    if ($userInfo['user_type'] == 2) return;
    // 如果当前userinfo中的uid有自己的邀请码， 则深入查询
    $sql         = 'SELECT id FROM ' . $invcodeTab . ' WHERE uid = ' . $uid;
    $codeData    = $db->getall($sql);
    if (!$codeData) return;
    $codeIdStr   = implode(',', array_column($codeData, 'id'));
    $sql         = 'SELECT uid FROM ' . $userinfoTab . ' WHERE invita_code_id IN (' . $codeIdStr . ')';
    $memberList  = $db->getall($sql);
    if (!$memberList) return;
    foreach ($memberList as $k => $v) {
        getUserLine($v['uid'], $data, $lv+1, $uid, $is_self);
    }
}

/**
 * 反推，注册时根据用户id反推所有的上级线
 */
function getUserLineUp($uid, &$data, $is_self=true){
    global $db;
    $sql      = 'SELECT uid, invita_code_id FROM ' . Table('user_info') . ' WHERE uid = ' . $uid;
    $userInfo = $db->getrow($sql);
    if (!$is_self){
        $data[$userInfo['uid']] = $userInfo;
    }
    $is_self = false;
    $sql      = 'SELECT uid FROM ' . Table('user_invita_code') . ' WHERE id = ' . $userInfo['invita_code_id'];
    $invCodeInfo = $db->getrow($sql);
    if ($invCodeInfo['uid'] <= 0) return;
    getUserLineUp($invCodeInfo['uid'], $data, $is_self);
}
